package com.ruoyi.activiti.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.task.IdentityLink;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class MyTaskListener implements TaskListener {

    public static String assignment = "assignment";
    public static String create = "create";
    public static String complete = "complete";
    public static String delete = "delete";

    @Autowired
    private RemoteUserService sysUserService;

    /**
     * 任务监听器会经历assignment、create、complete、delete。当流程引擎触发这四种事件类型时，
     * 对应的任务监听器会捕获其事件类型，再按照监听器的处理逻辑进行处理。
     *
     * @param delegateTask
     */
    @Override
    public void notify(DelegateTask delegateTask) {

        //需要初始化属性
        sysUserService = sysUserService == null ? sysUserService = SpringUtils.getBean(RemoteUserService.class) : sysUserService;

        if (create.equals(delegateTask.getEventName())) {//任务创建，发送通知
            notifyForTask(delegateTask);
        } else if (assignment.equals(delegateTask.getEventName())) {//任务转办，发送通知
            notifyForTask(delegateTask);
        }
    }

    private void notifyForTask(DelegateTask delegateTask) {
        Set<String> usernames = new HashSet<>();
        if (StringUtils.isNotEmpty(delegateTask.getAssignee())) {
            usernames.add(delegateTask.getAssignee());
        }
        if (CollectionUtil.isNotEmpty(delegateTask.getCandidates())) {
            for (IdentityLink candidate : delegateTask.getCandidates()) {
                if (StringUtils.isNotEmpty(candidate.getUserId())) {
                    usernames.add(candidate.getUserId());
                } else if (StringUtils.isNotEmpty(candidate.getGroupId())) {
                    R<List<SysUser>> r = sysUserService.selectUserListByRoleKey(candidate.getGroupId());
                    if (r != null && CollectionUtil.isNotEmpty(r.getData())) {
                        usernames.addAll(r.getData().stream().map(SysUser::getUserName).collect(Collectors.toSet()));
                    }
                }
            }
        }
        if (CollectionUtil.isEmpty(usernames)) {
            log.info("任务{}（{}）已创建，但没有处理人。", delegateTask.getName(), delegateTask.getId());
        }
    }
}
